package com.health.es.config;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.map.MapUtil;
import com.health.es.temp.EsClassOperations;
import com.health.es.util.ElasticsearchRestTemplate;
import com.health.es.util.IndexOperations;
import com.health.es.util.annotations.Document;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.PostConstruct;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author nqlz
 */
@Slf4j
@RequiredArgsConstructor
public class EsInit {
    private final AtomicInteger errorSize = new AtomicInteger(0);
    private final ElasticsearchRestTemplate template;
    private final EsClassOperations esClassOperations;

    @PostConstruct
    public void run() {
        if (esClassOperations==null) {
            log.error("spring bean 初始化出错");
        }
        long count = EsClassOperations.ES_CLASSES.stream()
                .filter(i -> i.isAnnotationPresent(Document.class))
                .peek(this::initIndex).count();
        log.info("Scan EsPojo Classes Size: {}", count);
        if (errorSize.get() > 0) {
            log.error("{}个线上索引mapping与实体索引是不一致，请检查", errorSize.get());
        }
    }

    public void initIndex(Class<?> cls) {
        IndexOperations indexOps = template.indexOps(cls);
        if (!indexOps.exists()) {
            if (indexOps.create()) {
                indexOps.putMapping(cls);
                indexOps.refresh();
            }
        }
        //检测索引异常
        else if (MapUtil.isEmpty(indexOps.getMapping())) {
            try {
                indexOps.putMapping(cls);
                indexOps.refresh();
            } catch (Exception e) {
                log.error("index :{}, create happened error: {}", cls.getSimpleName(), ExceptionUtil.getMessage(e));
            }
        }
        //校验线上索引与实体索引是否一致
        try {
            indexOps.putMapping(indexOps.createMapping(cls));
        } catch (Exception e) {
            log.error("索引 {} 与线上不一致。", cls.getSimpleName());
            errorSize.getAndIncrement();
        }
    }

}
